import { useEffect, useState } from 'react'
import { View, ScrollView } from '@tarojs/components'
// import { groupBy } from 'lodash'

import tools from '@/common/tools'
import { ERR_MES } from '@/common/constant'
import { cityReq } from '@/common/api'

import CityItem from './components/cityItem'

import './ariPortList.scss'

const AirPortList = () => {
  const [cityList, setCityList] = useState<object>({})
  const [currentLetter, setCurrentLetter] = useState<string>('')
  const [letterList, setLetterList] = useState<string[]>([])

  useEffect(() => {
    getCityList()
  }, [])

  const getCityList = async (): Promise<void> => {
    try {
      tools.showLoading()
  
      const storedFlightCityList = tools.getStorageSyncWithTime('flightCityList')?.result || []
  
      if (storedFlightCityList?.length) {
        parseCityList(storedFlightCityList)
      } else {
        const response = await cityReq()
  
        if (response.code === 200) {
          tools.setStorageSyncWithTime('flightCityList', response, 20)
          // 缓存机场数据到本地
          parseCityList(response.result || [])
        } else {
          tools.showToast(ERR_MES)
        }
      }
    } catch (error) {
      console.error(error)
      tools.showToast(ERR_MES)
    } finally {
      tools.hideLoading()
    }
  }

  const parseCityList = (list) => {
    function groupBy(array, key) {
      return array.reduce(function(result, item) {
        (result[item[key]] = result[item[key]] || []).push(item);
        return result;
      }, {});
    }
    const parsedData = groupBy(list, 'firstLetter') as object
    setCityList(parsedData || {})
    setLetterList(Object.keys(parsedData))
  }

  return (
    <View className='airport-list-container'>
      <ScrollView
        scrollY
        scrollWithAnimation={tools.isAlipay() ? false : true}
        scrollIntoView={currentLetter}
        style={{ height: '100vh' }}
      >
        {letterList.map((item) => (
          <CityItem key={item} label={item} cityList={cityList[item]} />
        ))}
      </ScrollView>
      <View className='letter-container'>
        {letterList.map((letter) => (
          <View key={letter} className='letter-item' onClick={() => setCurrentLetter(letter)}>
            {letter}
          </View>
        ))}
      </View>
    </View>
  )
}

export default AirPortList
